﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace SystemUpdatesCore.Server.Network
{
    public class NetworkHttpClient : INetworkClient
    {
        public string BaseAddress { get; set; }

        /// <summary>
        /// 异步下载文件完成事件
        /// </summary>
        public event AsyncCompletedEventHandler? DownloadFileCompleted;
        /// <summary>
        /// 异步下载文件进度改变事件
        /// </summary>
        public event NetworkDownloadProgressChangedEventHandler? DownloadProgressChanged;

        /// <summary>
        /// 异步获取字符串完成事件
        /// </summary>
        public event NetworkDownloadStringCompletedEventHandler? DownloadStringCompleted;

        public void DownloadFile(string address, string fileName)
        {
            throw new NotImplementedException();
        }

        public void DownloadFileAsync(Uri address, string fileName)
        {
            throw new NotImplementedException();
        }

        public Task DownloadFileTaskAsync(string address, string fileName)
        {
            return ReadAsync(address, fileName);
        }

        public string DownloadString(string address)
        {
            throw new NotImplementedException();
        }

        public void DownloadStringAsync(Uri address)
        {
            throw new NotImplementedException();
        }

        public Task<string> DownloadStringTaskAsync(string address)
        {
            return ReadAsStringAsync(address);
        }



        // HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
        static readonly HttpClient client = new HttpClient();

        async Task<string> ReadAsStringAsync(string address)
        {
            // Call asynchronous network methods in a try/catch block to handle exceptions.
            try
            {
                //using HttpResponseMessage response = await client.GetAsync(address);
                //response.EnsureSuccessStatusCode();
                //string responseBody = await response.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                string responseBody = await client.GetStringAsync(address);

                //Console.WriteLine(responseBody);
                return responseBody;
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("Message :{0} ", e.Message);
                throw e;
            }
        }

        async Task ReadAsync(string address, string fileName)
        {
            try
            {
                // 创建HttpClient实例
                //using (HttpClient client = new HttpClient())
                //{
                // 发送GET请求并获取响应流
                using (HttpResponseMessage response = await client.GetAsync(address, HttpCompletionOption.ResponseHeadersRead))
                using (Stream contentStream = await response.Content.ReadAsStreamAsync())
                {
                    // 获取文件总大小
                    long? totalBytes = response.Content.Headers.ContentLength;

                    byte[] buffer = new byte[4096];
                    long totalBytesRead = 0;
                    int bytesRead;

                    // 创建目标文件流
                    using (FileStream destinationStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            // 写入目标文件
                            await destinationStream.WriteAsync(buffer, 0, bytesRead);

                            // 更新进度条
                            totalBytesRead += bytesRead;
                            //if (totalBytes == null || totalBytes.HasValue)
                            //{
                            int progressPercentage = totalBytes == null ? -1 : (int)(totalBytesRead * 100 / totalBytes.Value);

                            var downloadProgress = new NetworkDownloadProgressChangedEventArgs(
                                  progressPercentage: progressPercentage,
                                  userToken: null,
                                  bytesReceived: bytesRead,
                                  totalBytesToReceive: totalBytesRead
                                );
                            DownloadProgressChanged?.Invoke(this, downloadProgress);
                            //}

                        }

                    }
                }
                //}
            }
            catch (Exception ex)
            {
                DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(ex, true, null));
                return;
            }

            DownloadFileCompleted?.Invoke(this, new AsyncCompletedEventArgs(null, true, null));
            Console.WriteLine("文件下载完成");
        }




    }
}
